package cn.lkp.mall.order.service.impl;
import cn.lkp.common.constant.CartConstant;
import cn.lkp.common.to.mq.SeckillOrderTo;
import cn.lkp.common.utils.R;
import cn.lkp.common.vo.MemberVo;
import cn.lkp.mall.order.constant.OrderConstant;
import cn.lkp.mall.order.constant.PayConstant;
import cn.lkp.mall.order.entity.PaymentInfoEntity;
import cn.lkp.mall.order.enums.OrderStatusEnum;
import cn.lkp.mall.order.entity.OrderItemEntity;
import cn.lkp.mall.order.feign.CartFeign;
import cn.lkp.mall.order.feign.MemberFeign;
import cn.lkp.mall.order.feign.ProductFeign;
import cn.lkp.mall.order.feign.WmsFeign;
import cn.lkp.mall.order.interceptor.LoginUserInterceptor;
import cn.lkp.mall.order.service.OrderItemService;
import cn.lkp.mall.order.service.PaymentInfoService;
import cn.lkp.mall.order.to.OrderCreateTo;
import cn.lkp.mall.order.to.OrderTo;
import cn.lkp.mall.order.to.SpuInfoTo;
import cn.lkp.mall.order.vo.*;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lkp.common.utils.PageUtils;
import cn.lkp.common.utils.Query;

import cn.lkp.mall.order.dao.OrderDao;
import cn.lkp.mall.order.entity.OrderEntity;
import cn.lkp.mall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    CartFeign cartFeign;
    @Autowired
    MemberFeign memberFeign;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    WmsFeign wmsFeign;
    @Autowired
    ProductFeign productFeign;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    BestPayService bestPayService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }
    /**
     * 订单确认页返回需要用到的数据
     * @return
     */
    @Override
    public OrderConfirmVo toTrade() throws ExecutionException, InterruptedException {
        //构建OrderConfirmVo
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //获取当前用户登录的信息
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        //获取当前线程请求头信息(解决Feign异步调用丢失请求头问题)
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        //开启第一个异步任务
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(attributes);
            //1、远程查询所有的收货地址列表
            List<MemberAddressVo> address = memberFeign.getAddress(memberVo.getId());
            //赋值
            orderConfirmVo.setMemberAddressVos(address);
        }, executor);
        //开启第二个异步任务
        CompletableFuture<Void> cartInfoFuture = CompletableFuture.runAsync(() -> {
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(attributes);
            //2. 远程查询购物车中选中的购物项
            List<OrderItemVo> itemVos = cartFeign.getCurrentCartItems();
            //赋值
            orderConfirmVo.setItems(itemVos);
            //feign在远程调用之前要构造请求，调用很多的拦截器
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map((itemVo -> itemVo.getSkuId())).collect(Collectors.toList());
            //3. 远程查询商品库存信息
            R hasStock = wmsFeign.getSkuHasStock(skuIds);
            List<SkuStockVo> skuStockVos = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if(skuStockVos != null){
                //将skuStockVos集合转换为map
                Map<Long, Boolean> skuHasStockMap = skuStockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId,
                        SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(skuHasStockMap);
            }
        },executor);
        //4. 获取用户积分信息
        Integer integration = memberVo.getIntegration();
        //赋值
        orderConfirmVo.setIntegration(integration);
        //5. 订单总额数据自动计算
        //6. 防重令牌，防止订单确认时重复提交，为用户设置一个token,存在redis中，设置三十分钟过期时间
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX +memberVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        //异步任务执行完毕后执行阻塞
        CompletableFuture.allOf(addressFuture,cartInfoFuture).get();
        return orderConfirmVo;
    }
    /**
     * 提交订单,加入事务
     * 本地式事务，在分布式系统，只能控制自己的回滚，控制不了其他服务的回滚
     * 分布式事务：最大原因：网络问题+分布式机器
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        //初始化当前线程后，将OrderSubmitVo加入当前线程
        confirmVoThreadLocal.set(vo);
        //构建responseVo
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        //设置登陆用户状态码为0
        responseVo.setCode(0);
        //获取当前用户的登陆信息
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        //去创建 下订单 验证令牌 验证价格 锁定库存
        //1、验证令牌是否合法【令牌的对比和删除必须保证原子性】0令牌失败，1令牌成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //这里和视频不一致，视频里面不需要强转为String
//        String redisToken = (String) redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
//        if(orderToken!=null && orderToken.equals(redisToken)){
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
//        }else {
//
//        }
//        //通过lure脚本原子验证令牌和删除令牌
        Long result = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()),
                orderToken);
        if (result == 0L) {
            //令牌验证失败,请刷新再次提交
            responseVo.setCode(1);
            return responseVo;
        } else {
            //令牌验证成功
            //1、创建订单、订单项等信息
            OrderCreateTo to = createOrder();
            //2、验证价格
            BigDecimal payAmount = to.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //金额对比
                //保存订单
                saveOrder(to);
                //库存锁定，只要有异常，就回滚订单数据
                //订单号、所有订单项信息(skuId,skuNum,skuName)
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(to.getOrder().getOrderSn());
                //获取出要锁定的商品数据信息
                List<OrderItemVo> orderItemVos = to.getOrderItems().stream().map((item) -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                //TODO 调用远程锁定库存的方法
                //出现的问题：扣减库存成功了，但是由于网络原因超时，出现异常，导致订单事务回滚，库存事务不回滚(解决方案：seata)
                //为了保证高并发，不推荐使用seata，因为是加锁，并行化，提升不了效率,可以发消息给库存服务
                //库存服务本身也可以使用自动解锁模式
                R r = wmsFeign.orderLockStock(wareSkuLockVo);
                if(r.getCode()==0){
                    //锁定成功
                    responseVo.setOrder(to.getOrder());
                    //TODO 远程扣减积分
                    //发送信息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",to.getOrder());
                    redisTemplate.delete(CartConstant.CART_PREFIX+memberVo.getId());
                    return responseVo;
                }else {
                    //库存锁定失败，商品库存不足
                    //String msg = (String) r.get("msg");
                    //throw new NoStockException(msg);
                    responseVo.setCode(3);
                    return responseVo;
                }
            }else{
                //订单商品价格发生变化，请确认后再次提交
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }


    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //关闭订单之前先查询一下数据库，判断此订单状态是否已支付
        OrderEntity orderInfo = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderEntity.getOrderSn()));
        if(orderInfo.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            //处于待付款状态的进行关单
            OrderEntity update = new OrderEntity();
            update.setId(orderInfo.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
        }
        //发送消息给MQ
        OrderTo orderTo = new OrderTo();
        BeanUtils.copyProperties(orderInfo,orderTo);
        try{
            //TODO 确保每个消息发送成功，给每个消息做好日志记录，(给数据库保存每一个详细信息)保存每个消息的详细信息
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }catch (Exception e){
            //TODO 定期扫描数据库，重新发送失败的消息
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    /**
     * 获取当前订单的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderInfo = this.getOrderByOrderSn(orderSn);
        //保留两位小数点，向上取值（数据库中付款金额为BigDecimal 4位，支付宝付款金额只能为2位，所以保留2位）
        BigDecimal payAmount = orderInfo.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());
        payVo.setOut_trade_no(orderInfo.getOrderSn());
        //查询订单项的数据
        List<OrderItemEntity> orderItemInfo = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemInfo.get(0);
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        payVo.setSubject(orderItemEntity.getSkuName());
        return payVo;
    }
    /**
     * 处理支付宝的支付结果
     * @param asyncVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        //添加到数据库中
        //数据中添加索引，一个订单号（对外业务号）和一个支付宝交易流水号只对应一条交易流水。
        //订单号（对外业务号）`order_sn`和支付宝交易流水号`alipay_trade_no`设置唯一索引。
        this.paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = asyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            this.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
            //TODO 支付成功后发送消息，删掉购物车中本次支付成功的购物项
        }

        return "success";
    }

    @Override
    public String asyncNotify(String notifyData) {
        //签名效验
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("payResponse={}",payResponse);

        //2.金额效验（从数据库查订单）
        OrderEntity orderEntity = this.getOrderByOrderSn(payResponse.getOrderId());

        //如果查询出来的数据是null的话
        //比较严重(正常情况下是不会发生的)发出告警：钉钉、短信
        if (orderEntity == null) {
            //TODO 发出告警，钉钉，短信
            throw new RuntimeException("通过订单编号查询出来的结果是null");
        }

        //判断订单状态状态是否为已支付或者是已取消,如果不是订单状态不是已支付状态
        Integer status = orderEntity.getStatus();
        if (status.equals(OrderStatusEnum.PAYED.getCode()) || status.equals(OrderStatusEnum.CANCLED.getCode())) {
            throw new RuntimeException("该订单已失效,orderNo=" + payResponse.getOrderId());
        }

        /*//判断金额是否一致,Double类型比较大小，精度问题不好控制
        if (orderEntity.getPayAmount().compareTo(BigDecimal.valueOf(payResponse.getOrderAmount())) != 0) {
            //TODO 告警
            throw new RuntimeException("异步通知中的金额和数据库里的不一致,orderNo=" + payResponse.getOrderId());
        }*/

        //3.修改订单支付状态
        //支付成功状态
        String orderSn = orderEntity.getOrderSn();
        this.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(),PayConstant.WXPAY);

        //4.告诉微信不要再重复通知了
        return "<xml>\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }

    @Override
    public void updateOrderStatus(String orderSn, Integer code, Integer payType) {
        this.baseMapper.updateOrderStatus(orderSn,code,payType);
    }
    /**
     * 查询当前用户所有订单数据
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id",memberVo.getId()).orderByDesc("create_time")
        );

        //遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            //根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);

        return new PageUtils(page);
    }

    /**
     * 创建秒杀单
     * @param orderTo
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);

        orderItem.setSkuQuantity(orderTo.getNum());

        //保存商品的spu信息
        R spuInfo = productFeign.getSpuInfoBySkuId(orderTo.getSkuId());
        SpuInfoTo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoTo>() {
        });
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setSpuBrand(spuInfoData.getBrandName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }

    private void saveOrder(OrderCreateTo to) {
        //获取订单信息
        OrderEntity orderEntity = to.getOrder();
        orderEntity.setModifyTime(new Date());
        orderEntity.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(orderEntity);
        //获取订单项信息
        List<OrderItemEntity> orderItems = to.getOrderItems();
        //批量保存订单数据
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder(){
        //实例化创建订单的to
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //自定义方法，返回订单实体类
        OrderEntity orderEntity = builderOrder(orderSn);
        //将订单实体类赋值给创建订单的to
        orderCreateTo.setOrder(orderEntity);
        //2.自定义方法，获取订单所有购物项信息，赋值给创建订单的to
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn);
        orderCreateTo.setOrderItems(orderItemEntities);
        //3. 验价（计算价格、积分等信息）
        computerPrice(orderEntity,orderItemEntities);
        return orderCreateTo;
    }

    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        //积分 成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            //优惠价
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            //总价
            total = total.add(orderItemEntity.getRealAmount());
            //积分 成长值
            integrationTotal += orderItemEntity.getGiftIntegration();
            growthTotal += orderItemEntity.getGiftGrowth();
        }
        //设置订单价格
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //设置优惠价
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setPromotionAmount(promotion);
        //设置积分成长值
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);
        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);
    }

    private List<OrderItemEntity> builderOrderItems(String orderSn) {
        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();
        //1.最后确定每一个订单项的价格
        List<OrderItemVo> vos = cartFeign.getCurrentCartItems();
        if (vos != null && vos.size()>0) {
            orderItemEntityList = vos.stream().map((items) -> {
                //构建订单项数据
                OrderItemEntity orderItemEntity = builderOrderItem(items);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntityList;
    }
    /**
     * 构建某一个订单项的数据
     * @param items
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo items) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1.商品spu信息
        Long skuId = items.getSkuId();
        R spuInfo = productFeign.getSpuInfoBySkuId(skuId);
        //2.商品的spu信息
        SpuInfoTo spuInfoTo = spuInfo.getData("data",new TypeReference<SpuInfoTo>(){});
        orderItemEntity.setSpuId(spuInfoTo.getId());
        orderItemEntity.setSpuName(spuInfoTo.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoTo.getBrandName());
        orderItemEntity.setCategoryId(spuInfoTo.getCatalogId());
        //3.商品的sku信息
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToCommaDelimitedString(items.getSkuAttrs()));
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());
        //4.商品的优惠信息
        //5.商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        //6.订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        //当前订单项的实际金额， 总额-各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getCouponAmount()).
                subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);
        return orderItemEntity;
    }

    /**
     * 构建订单数据
     * @param orderSn
     * @return
     */
    private OrderEntity builderOrder(String orderSn){
        //获取当前用户登录信息
        MemberVo memberVo= LoginUserInterceptor.loginUser.get();
        //将当前用户登录信息赋值给订单相应字段
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberVo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberVo.getUsername());
        //取出当前线程中的OrderSubmitVo
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        //远程调用会员服务获取运费vo,里面封装了会员地址信息vo和运费字段
        R r = wmsFeign.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData("data", new TypeReference<FareVo>() {
        });
        //获取运费值
        BigDecimal fare = fareVo.getFare();
        //将运费字段值赋值给订单中的对应字段
        orderEntity.setFreightAmount(fare);
        //从运费vo中获取到会员收货地址vo
        MemberAddressVo vo = fareVo.getAddress();
        //将会员收货地址vo里面的字段值赋值给订单实体类中的对应字段。
        orderEntity.setReceiverCity(vo.getCity());
        orderEntity.setReceiverDetailAddress(vo.getDetailAddress());
        orderEntity.setReceiverName(vo.getName());
        orderEntity.setReceiverPhone(vo.getPhone());
        orderEntity.setReceiverPostCode(vo.getPostCode());
        orderEntity.setReceiverProvince(vo.getProvince());
        orderEntity.setReceiverRegion(vo.getRegion());
        //设置订单相关的订单信息：订单状态，自动确认，默认设置未确认收货
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }
}